package com.config.service.impl;

import cn.hutool.core.util.StrUtil;
import com.config.entity.Courses;
import com.config.entity.Students;
import com.config.entity.StudentsExample;
import com.config.mapper.CoursesMapper;
import com.config.mapper.StudentsMapper;
import com.config.service.StudentsService;
import com.config.vo.StudentVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.config.util.PageResult;

import java.util.List;


@Service
public class StudentsServiceImpl implements StudentsService {
	@Autowired
	private StudentsMapper studentsMapper;
	@Autowired
	private CoursesMapper coursesMapper;
	// 1. 查询所有学生
	@Override
	public List<Students> findAll() {
		List<Students> students = studentsMapper.selectByExample(null);
		students.forEach(st -> {
			Courses courses = coursesMapper.selectByPrimaryKey(st.getCid());
			st.setCname(courses.getCname());
		});
		return students;
	}

	@Override
	public PageResult<Students> findByPage(Integer page, Integer pageSize) {
		//1. 开始分页
		PageHelper.startPage(page,pageSize);
		// 2. 开始查询数据
		List<Students> students = this.findAll();
		// 3. 将查询得到的数据转换为Page<Student>对象
		Page<Students> studentPage = (Page<Students>) students;
		// 4. 转换为PageResult对象studentPage.getResult(),studentPage.getTotal()
		return new PageResult<>(studentPage.getResult(),studentPage.getTotal());

	}
	// 条件查询带分页功能
	@Override
	public PageResult<Students> search(Integer page, Integer pageSize, StudentVO studentVo) {
		// 1. 开始分页
		PageHelper.startPage(page, pageSize);
		// 2. 查询数据
		// 2.1 定义一次查询的实例
		StudentsExample example = new StudentsExample();
		// 2.2 添加查询条件到查询实例中
		StudentsExample.Criteria criteria = example.createCriteria();
		if(StrUtil.isNotBlank(studentVo.getSname())){
			criteria.andSnameLike("%" + studentVo.getSname() + "%");
		}
		if(StrUtil.isNotBlank(studentVo.getAddr())){
			criteria.andAddrLike("%" + studentVo.getAddr() + "%"); // addr like '%' + addr + '%'
		}
		if(studentVo.getCid() != null && studentVo.getCid() != 0){
			criteria.andCidEqualTo(studentVo.getCid());
		}
		List<Students> students = studentsMapper.selectByExample(example);
		// 2.3 处理学生班级
		students.forEach(st -> {
			Courses classes = coursesMapper.selectByPrimaryKey(st.getCid());
			st.setCname(classes.getCname());
		});

		// 2.4 将上面的students对象转换为List集合
		Page<Students> studentPage = (Page<Students>) students;
		return new PageResult<>(studentPage.getResult(),studentPage.getTotal());

	}

	// 3. 添加学生
	@Override
	public boolean save(Students students) {
		return studentsMapper.insert(students) > 0;
	}
}
